package demo.controller;

import demo.dao.FileDao;
import demo.dao.UserDao;
import demo.entity.LargeFile;
import demo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/home")
public class LoginController {
@Autowired(required = false)
    UserDao userDao;
    @Autowired(required = false)
    FileDao fileDao;
    @GetMapping("/go2login")
    public String go2Login(Model model) {//初始跳转页面显示
        model.addAttribute("loginok","请登录......");//显示未登录
        return "login";//跳转登录页面
    }
    @PostMapping("/login")
    public String login(User user,HttpSession session, Model model){//获取登录信息
            User user1=userDao.findByPhone(user.getPhone());//拿到数据库里对应的客户信息
        if (user==null){//判断从数据库拿得到的信息是否为空
            model.addAttribute("loginok","登录失败,账号不存在");//返回登录失败
            return "login";//跳转回登录页面
        }
        if (!user.getPwd().equals(user1.getPwd())||user.getPwd()==null){//判断用户输入的密码跟数据库里的密码做判断
            model.addAttribute("loginok","登录失败,密码错误");//返回失败
            return "login";//跳转回登录页面
        }
        user1.setPwd("");//将数据库的密码设置为空
        session.setAttribute("DL",user1);//设置登录成功标志将用户放在session
        model.addAttribute("loginok","登录成功");//显示成功
        return "login";//跳转回登录页面
    }
    @GetMapping("/loginout")
    public String loginout(HttpSession session,Model model){//退出登录页面
//        HttpSession session 是直接绑定getsession
        System.out.println("销毁对象");
        session.invalidate();//销毁对象
        model.addAttribute("loginok","退出成功");//显示退出成功
        return "login";//跳转回登录页面
    }
    @GetMapping("/shows/{uuid}")
    public void ShowPic(@PathVariable("uuid") String id, HttpServletResponse response , Model model) throws Exception{//显示照片
        LargeFile one = fileDao.findOne(id);
        Object content = one.getContent();
        ServletOutputStream outputStream = response.getOutputStream();
        response.setContentType("image/jpeg");
        byte[] bytes=(byte[]) content;
        outputStream.write(bytes);
        outputStream.flush();
    }
}
